package com.fiberhome.nas.feature.taskcenter.view

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fiberhome.nas.core.designsystem.theme.BgGreyLight
import com.fiberhome.nas.core.designsystem.theme.BodyLarge
import com.fiberhome.nas.core.designsystem.theme.Primary
import com.fiberhome.nas.core.model.entity.TaskStatus
import com.fiberhome.nas.core.model.entity.UploadTask
import com.fiberhome.nas.core.ui.component.scaffold.AppScaffold
import com.fiberhome.nas.core.util.file.FileUtils
import com.fiberhome.nas.feature.taskcenter.viewmodel.TaskCenterViewModel

/**
 * 任务中心路由入口
 */
@Composable
fun TaskCenterRoute(
    viewModel: TaskCenterViewModel = hiltViewModel()
) {
    val uploadTasks by viewModel.uploadTasks.collectAsStateWithLifecycle()
    val downloadTasks by viewModel.downloadTasks.collectAsStateWithLifecycle()
    val selectedTabIndex by viewModel.selectedTabIndex.collectAsStateWithLifecycle()
    val isEditMode by viewModel.isEditMode.collectAsStateWithLifecycle()
    val selectedTaskIds by viewModel.selectedTaskIds.collectAsStateWithLifecycle()

    TaskCenterScreen(
        uploadTasks = uploadTasks,
        downloadTasks = downloadTasks,
        selectedTabIndex = selectedTabIndex,
        isEditMode = isEditMode,
        selectedTaskIds = selectedTaskIds,
        onTabSelected = viewModel::setSelectedTabIndex,
        onTaskLongClick = { viewModel.toggleEditMode() },
        onTaskClick = { taskId ->
            if (isEditMode) {
                viewModel.toggleTaskSelection(taskId)
            }
        },
        onBackClick = { viewModel.toggleEditMode() },
        onSelectAllClick = { viewModel.selectAll() },
        onClearSelectionClick = { viewModel.deselectAll() },
        onDeleteClick = { viewModel.deleteSelectedTasks() },
        onPauseTask = viewModel::pauseUploadTask,
        onResumeTask = viewModel::resumeUploadTask,
        onRetryTask = viewModel::resumeUploadTask
    )
}

/**
 * 任务中心屏幕
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskCenterScreen(
    uploadTasks: List<UploadTask>,
    downloadTasks: List<UploadTask>,
    selectedTabIndex: Int,
    isEditMode: Boolean,
    selectedTaskIds: Set<String>,
    onTabSelected: (Int) -> Unit,
    onTaskLongClick: () -> Unit,
    onTaskClick: (String) -> Unit,
    onBackClick: () -> Unit,
    onSelectAllClick: () -> Unit,
    onClearSelectionClick: () -> Unit,
    onDeleteClick: () -> Unit,
    onPauseTask: (String) -> Unit,
    onResumeTask: (String) -> Unit,
    onRetryTask: (String) -> Unit
) {
    AppScaffold(
        topBar = {
            if (isEditMode) {
                EditModeTopBar(
                    selectedCount = selectedTaskIds.size,
                    onBackClick = onBackClick,
                    onSelectAllClick = onSelectAllClick,
                    onClearSelectionClick = onClearSelectionClick
                )
            } else {
                CenterAlignedTopAppBar(
                    title = { Text("任务中心") },
                    navigationIcon = {
                        IconButton(onClick = { /* 返回上一页 */ }) {
                            Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                        }
                    }
                )
            }
        },
        bottomBar = {
            if (isEditMode) {
                EditModeBottomBar(
                    onDeleteClick = onDeleteClick
                )
            }
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // 标签页
            ScrollableTabRow(
                selectedTabIndex = selectedTabIndex,
                indicator = { tabPositions ->
                    TabRowDefaults.Indicator(
                        modifier = Modifier.tabIndicatorOffset(tabPositions[selectedTabIndex]),
                        color = Primary
                    )
                }
            ) {
                Tab(
                    selected = selectedTabIndex == 0,
                    onClick = { onTabSelected(0) },
                    text = { Text("上传") }
                )
                Tab(
                    selected = selectedTabIndex == 1,
                    onClick = { onTabSelected(1) },
                    text = { Text("下载") }
                )
            }

            // 任务列表
            Box(modifier = Modifier.fillMaxSize()) {
                val tasks = if (selectedTabIndex == 0) uploadTasks else downloadTasks

                if (tasks.isEmpty()) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("暂无任务")
                    }
                } else {
                    TaskList(
                        tasks = tasks,
                        isEditMode = isEditMode,
                        selectedTaskIds = selectedTaskIds,
                        onTaskLongClick = onTaskLongClick,
                        onTaskClick = onTaskClick,
                        onPauseTask = onPauseTask,
                        onResumeTask = onResumeTask,
                        onRetryTask = onRetryTask
                    )
                }

                // 清空按钮
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                        .align(Alignment.BottomCenter)
                ) {
                    if (!isEditMode && tasks.isNotEmpty()) {
                        val completedTasks = tasks.filter { it.status is TaskStatus.Completed }
                        if (completedTasks.isNotEmpty()) {
                            TextButton(
                                onClick = { /* 清空已完成 */ },
                                modifier = Modifier.align(Alignment.Center)
                            ) {
                                Text("清空")
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 任务列表
 */
@Composable
fun TaskList(
    tasks: List<UploadTask>,
    isEditMode: Boolean,
    selectedTaskIds: Set<String>,
    onTaskLongClick: () -> Unit,
    onTaskClick: (String) -> Unit,
    onPauseTask: (String) -> Unit = {},
    onResumeTask: (String) -> Unit = {},
    onRetryTask: (String) -> Unit = {}
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(bottom = 80.dp) // 为底部按钮留出空间
    ) {
        items(tasks) { task ->
            TaskItemCard(
                task = task,
                isEditMode = isEditMode,
                isSelected = selectedTaskIds.contains(task.id),
                onTaskLongClick = onTaskLongClick,
                onTaskClick = { onTaskClick(task.id) },
                onPauseTask = onPauseTask,
                onResumeTask = onResumeTask,
                onRetryTask = onRetryTask
            )
        }
    }
}

/**
 * 任务项卡片
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TaskItemCard(
    task: UploadTask,
    isEditMode: Boolean,
    isSelected: Boolean,
    onTaskLongClick: () -> Unit,
    onTaskClick: () -> Unit,
    onPauseTask: (String) -> Unit = {},
    onResumeTask: (String) -> Unit = {},
    onRetryTask: (String) -> Unit = {}
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
            .combinedClickable(
                onClick = onTaskClick,
                onLongClick = onTaskLongClick
            ),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) BgGreyLight else MaterialTheme.colorScheme.surface
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 选择框（编辑模式下显示）
            if (isEditMode) {
                Box(
                    modifier = Modifier
                        .size(24.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(if (isSelected) Primary else Color.LightGray),
                    contentAlignment = Alignment.Center
                ) {
                    if (isSelected) {
                        Icon(
                            imageVector = Icons.Default.Check,
                            contentDescription = "已选择",
                            tint = Color.White,
                            modifier = Modifier.size(16.dp)
                        )
                    }
                }
                Spacer(modifier = Modifier.width(16.dp))
            }

            // 文件图标
            Icon(
                imageVector = Icons.Default.Refresh,
                contentDescription = null,
                tint = Primary
            )

            Spacer(modifier = Modifier.width(16.dp))

            // 文件信息
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = task.fileName,
                    style = BodyLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )

                Spacer(modifier = Modifier.height(4.dp))

                // 进度条（仅上传中和下载中显示）
                if (task.status is TaskStatus.Uploading || task.status is TaskStatus.Downloading) {
                    LinearProgressIndicator(
                        progress = { (task.uploadedSize * 100f / task.totalSize) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(4.dp),
                        color = Primary,
                    )

                    Spacer(modifier = Modifier.height(4.dp))
                }

                // 状态信息
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = "${FileUtils.formatFileSize(task.uploadedSize)} / ${
                            FileUtils.formatFileSize(task.totalSize)
                        }",
//                        style = TextSecondaryLight,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )

                    if (task.labelTip.isNotEmpty()) {
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = task.labelTip,
//                            style = TextSecondaryLight,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            // 状态图标
            if (!isEditMode) {
                when (task.status) {
                    is TaskStatus.Uploading, is TaskStatus.Downloading -> {
                        IconButton(onClick = { onPauseTask(task.id) }) {
                            Icon(
                                imageVector = Icons.Default.Pause,
                                contentDescription = "暂停",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    is TaskStatus.Paused -> {
                        IconButton(onClick = { onResumeTask(task.id) }) {
                            Icon(
                                imageVector = Icons.Default.PlayArrow,
                                contentDescription = "继续",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    is TaskStatus.Failed -> {
                        IconButton(onClick = { onRetryTask(task.id) }) {
                            Icon(
                                imageVector = Icons.Default.Refresh,
                                contentDescription = "重试",
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    else -> {}
                }
            }
        }
    }
}

/**
 * 编辑模式顶部栏
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditModeTopBar(
    selectedCount: Int,
    onBackClick: () -> Unit,
    onSelectAllClick: () -> Unit,
    onClearSelectionClick: () -> Unit
) {
    TopAppBar(
        title = { Text("已选择 $selectedCount") },
        navigationIcon = {
            IconButton(onClick = onBackClick) {
                Icon(Icons.Default.Close, contentDescription = "关闭")
            }
        },
        actions = {
            TextButton(onClick = if (selectedCount > 0) onClearSelectionClick else onSelectAllClick) {
                Text(if (selectedCount > 0) "全部取消" else "全选")
            }
        }
    )
}

/**
 * 编辑模式底部栏
 */
@Composable
fun EditModeBottomBar(
    onDeleteClick: () -> Unit
) {
    BottomAppBar {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            IconButton(
                onClick = onDeleteClick,
                modifier = Modifier.weight(1f)
            ) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Icon(Icons.Default.Delete, contentDescription = "删除")
                    Text("删除")
                }
            }
        }
    }
}